package com.zhj.helloframework.mvc.processer.impl;

import com.zhj.helloframework.mvc.RequestProcessorChain;
import com.zhj.helloframework.mvc.processer.RequestProcessor;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;

/**
 * @Author: zhj
 * @Description: jsp资源请求处理器
 * @Date: 2021/11/16 16:56
 * @Version: 1.0
 */
public class JspRequestProcessor implements RequestProcessor {
    // jsp请求的RequestDispatcher的名称
    private static final String JSP_SERVLET = "jsp";
    // Jsp请求资源路径前缀
    private static final String JSP_RESOURCE_PREFIX = "/templates/";

    // jsp的RequestDispatcher,处理jsp资源
    private RequestDispatcher jspServlet;

    public JspRequestProcessor(ServletContext servletContext) {
        jspServlet = servletContext.getNamedDispatcher(JSP_SERVLET);
        if (jspServlet == null) {
            throw new RuntimeException("there is no jsp servlet");
        }
    }

    @Override
    public boolean process(RequestProcessorChain requestProcessorChain) throws Exception {
        // 1.判断请求路径判断是否是请求的jsp资源 /templates/
        if (isJspResource(requestProcessorChain.getRequestPath())) {
            // 2.如果是jsp资源，则进行请求转发，并返回false
            jspServlet.forward(requestProcessorChain.getRequest(), requestProcessorChain.getResponse());
            return false;
        }
        return true;
    }

    // 是否请求的是jsp资源
    public boolean isJspResource(String url) {
        return url.startsWith(JSP_RESOURCE_PREFIX);
    }
}
